package com.eclipseutilplugin.libplugin;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.ClasspathContainerInitializer;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.osgi.framework.Bundle;



public class AbstractClasspathInitilar extends ClasspathContainerInitializer {

	public AbstractClasspathInitilar(String id,String[][] jardata, String nm) {

		this.id = id;
		this.data = jardata;
		this.nm = nm;
	}
	String nm = "";

	String[][] data = new String[][] {};

	String id = null;

	public static IPath getPath() {

		Bundle bundel = Activator.getDefault().getBundle();
		if (bundel != null) {

			URL entry = bundel.getEntry("/");

			try {
				URL local = FileLocator.toFileURL(entry);

				return Path.fromOSString(new File(local.getPath()).getAbsolutePath());

			} catch (IOException e) {
				e.printStackTrace();
				return null;

			}

		}

		return null;
	}

	public IClasspathEntry[] createClasspathEntry() {

		IPath libpath = getPath();

		IClasspathEntry[] entry = new IClasspathEntry[data.length];

		for (int i = 0; i < data.length; i++) {
			String[] d = data[i];
			entry[i] = JavaCore.newLibraryEntry(libpath.append(d[0]), libpath.append(d[1]), null);

		}
		return entry;

	}

	public void initialize(final IPath containerPath, IJavaProject project) throws CoreException {
		int size = containerPath.segmentCount();
		if (size > 0) {
			if (containerPath.segment(0).equals(id)) {
				final IPath variablePath = getPath();
				if (variablePath == null) {
					return;
				}
				JavaCore.setClasspathContainer(containerPath, new IJavaProject[] { project }, new IClasspathContainer[] { new IClasspathContainer() {
					public IClasspathEntry[] getClasspathEntries() {

						return createClasspathEntry();
					}

					public String getDescription() {
						return nm;
					}

					public int getKind() {
						return IClasspathContainer.K_APPLICATION;
					}

					public IPath getPath() {
						return containerPath;
					}
				} }, null);
			}
		}
	}

}
